package com.chens.modules.system.controller;

import com.chens.common.controller.BaseController;
import com.chens.modules.system.model.User;
import com.chens.payload.ApiResponse;
import com.chens.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/sys/users")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    // 获取所有用户 - 需要管理员权限
    @GetMapping
    public ApiResponse<Page<User>> getUsers(@RequestParam(defaultValue = "0") int page,
                                            @RequestParam(defaultValue = "10") int size) {
        return ApiResponse.success(userService.getUsers(page, size));
    }

    // 获取单个用户
    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        return userService.getUserById(id)
                .map(ApiResponse::success)
                .orElse(ApiResponse.error(200, "User not found with id " + id));
    }

    // 创建新用户
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ApiResponse<User> createUser(@RequestBody User user) throws RuntimeException{
        return ApiResponse.success(userService.registerUser(user));
    }

    // 更新用户 - 需要管理员权限
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        try {
            User updatedUser = userService.updateUser(id, userDetails);
            return ApiResponse.success(updatedUser);
        } catch (RuntimeException e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    // 删除用户 - 需要管理员权限
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ApiResponse.success(null);
    }
}